/****************************************************
	文件：RefCounter.cs
	作者：HuskyT
	邮箱：1005240602@qq.com
	日期：2020/9/27 15:51:32
	功能：引用计数
*****************************************************/

namespace HTUtility
{
    public abstract class RefCounter : IRC
    {
        protected ReactiveProperty<int> mRefCount = new ReactiveProperty<int>();
        /// <summary>
        /// 引用计数
        /// </summary>
        public int RefCount => mRefCount.Value;

        public RefCounter()
        {
            InstallRC();
        }

        /// <summary>
        /// 增加引用计数
        /// </summary>
        /// <param name="addNum">增加的个数</param>
        public void Retain(int addNum = 1)
        {
            mRefCount.Value += addNum;
        }
        /// <summary>
        /// 减少引用计数
        /// </summary>
        /// <param name="minusNum">减少的个数</param>
        public void Release(int minusNum = 1)
        {
            mRefCount.Value -= minusNum;
        }
        /// <summary>
        /// 引用计数为0，对象的释放
        /// </summary>
        public abstract void OnDispose();
        /// <summary>
        /// 初始化引用计数
        /// </summary>
        protected void InstallRC()
        {
            mRefCount.Subscribe((count) =>
            {
                if (count <= 0)
                {
                    OnDispose();
                }
            });
        }
    }
}
